<script>
export default {
  name: 'viewer',
  data() {
    return {
      showJson: true,
      showCode: false
    }
  },
  props: {
    componentConfig: {
      type: Object,
      default: () => ({
        component: { template: '<el-skeleton></el-skeleton>' },
        sourceCode: '<template><el-skeleton></el-skeleton></template>',
        json: {}
      })
    },
    theme: { type: String, default: 'dark' }, //light
    renderToolbar: { type: Function },
    errorHandler: { type: Function },
    debounceDelay: {
      type: Number,
      default: 300
    }
  },
  computed: {},
  methods: {
    handleJsonChange(val) {
      this.$emit('jsonChange', val)
    },
    handleCodeChange(val) {
      this.$emit('codeChange', val)
    },
    viewJson() {
      this.showJson = !this.showJson
      this.showCode = false
    },
    viewCode() {
      this.showCode = !this.showCode
      this.showJson = false
    },
    renderPreview() {
      let sourceCode = this.componentConfig.sourceCode
      let sourceJosn = JSON.stringify(this.componentConfig.json, null, 2)
      const previewer = this.componentConfig.component
      return (
        <el-card>
          <el-card shadow="always" body-style={{ padding: '10px', border: '1px solid red' }}>
            <previewer></previewer>
          </el-card>

          <el-button type="text" on-click={this.viewJson}>
            json
          </el-button>
          <el-button type="text" on-click={this.viewCode}>
            vue
          </el-button>

          {this.showJson && <r-code-editor line-numbers codeHandler={this.handleJsonChange} theme={`base16-${this.theme}`} mode="text/javascript" value={sourceJosn} />}
          {this.showCode && <r-code-editor line-numbers codeHandler={this.handleCodeChange} theme={`base16-${this.theme}`} value={sourceCode} />}
        </el-card>
      )
    }
  },
  render() {
    return <div>{this.renderPreview()}</div>
  }
}
</script>


<style lang="css">
.code-view-wrapper {
  position: relative;
  margin: 18px 0;
  padding: 0;
  border: 1px solid #ebebeb;
  border-radius: 4px;
}
.code-view {
  padding: 18px;
}
.code-view-error {
  padding: 18px;
  color: red;
  max-height: 200px;
}

.code-view-toolbar {
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.CodeMirror {
  text-align: left;
  padding: 10px;
  height: auto !important;
}

.vue-code-transparent .code-view {
  background-image: linear-gradient(45deg, rgb(249, 249, 250) 25%, transparent 25%), linear-gradient(135deg, rgb(249, 249, 250) 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, rgb(249, 249, 250) 75%), linear-gradient(135deg, transparent 75%, rgb(249, 249, 250) 75%);
  background-size: 20px 20px;
  background-position: 0px 0px, 10px 0px, 10px -10px, 0px 10px;
}
</style>
